#include <stdio.h> 
#include <unistd.h> 
#include "ohos_init.h" 
#include "cmsis_os2.h" 
#include "iot_gpio.h" 
#include "iot_gpio_ex.h" 
#include "iot_uart.h" 
#include <hi_gpio.h>
#include <hi_io.h>
#include <hi_uart.h>
#include "hx711.h"
#include "crc16.h"
#include "hi_time.h"
#include "items_msg.h"
#include "iot_log.h"

Taurus_Msg rfid_msg_show;
//unsigned int rfid_queueID;
int rfid_state;
extern int weight_state;
extern int rfid_flag;
extern float commodity_weight;

unsigned char rfidReadBuff[2048] = {0};
unsigned char Rubbish[2048] = {0};

#define DEMO_UART_NUM2  HI_UART_IDX_2
#define ITEM_BOUNDARY 32768 //小于：按单价结算 大于等于：按重量结算

int RFID_Receive(Taurus_Msg *rfid_msg, hi_u8 *uart_data , hi_u16 uart_len);
int RFID_deal(Taurus_Msg *rfid_msg, hi_u8 *data, hi_u16 len);

static void Uart2GpioCOnfig(void)
{
    IoSetFunc(IOT_IO_NAME_GPIO_11, IOT_IO_FUNC_GPIO_11_UART2_TXD);
    IoSetFunc(IOT_IO_NAME_GPIO_12, IOT_IO_FUNC_GPIO_12_UART2_RXD);
}


int usr_uart_config2(void) 
{ 
    int ret; 
 
    //初始化UART配置，115200，数据bit为8,停止位1，奇偶校验为NONE，流控为NONE 
    IotUartAttribute uartAttr2 = {
        .baudRate = 115200, 
        .dataBits = 8, 
        .stopBits = 1, 
        .parity = 0,
    }; 
    ret = IoTUartInit(DEMO_UART_NUM2, &uartAttr2); 
    if (ret != 0) {
        printf("uart2 init fail = %d\r\n", ret);  
    } 
    return ret; 
} 

hi_u16 crc16_check(hi_u8 *ptr,hi_u16 len)
{
    hi_u16 crc = 0xffff;
    
    while(len--) 
    {
        crc = (crc << 8) ^ crc16_table[(crc >> 8 ^ *ptr++) & 0xff];
    }
    
    return (~crc) & 0xFFFF;
}

#define ADD  1  //添加商品
#define SUB  0  //删除商品

void RFID_write(hi_u8 wr_data)
{
    hi_u8 sel_code[]= {0xBB ,0x00 ,0x0C ,0x00 ,0x07 ,0x23 ,0x00 ,0x00 ,0x00 ,0x00 ,0x60 ,0x00 ,0x96 ,0x7E };
    hi_u8 wr0_code[]= {0xBB ,0x00 ,0x49 ,0x00 ,0x0B ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0x00 ,0x04 ,0x00 ,0x01 ,0x00 ,0x00 ,0x5A ,0x7E };
    hi_u8 wr1_code[]= {0xBB ,0x00 ,0x49 ,0x00 ,0x0B ,0x00 ,0x00 ,0x00 ,0x00 ,0x01 ,0x00 ,0x04 ,0x00 ,0x01 ,0x00 ,0x01 ,0x5B ,0x7E };
    hi_u16 len;
    hi_u8 wr_flag;
    unsigned char buffer[32] = {0};
    IoTUartWrite(DEMO_UART_NUM2, sel_code, sizeof(sel_code));
    do{
        hi_sleep(50);
        len = IoTUartRead(DEMO_UART_NUM2, buffer, sizeof(buffer));
    }while(len == 0);
    do{
        wr_flag = 0;
        if(wr_data == ADD)      IoTUartWrite(DEMO_UART_NUM2, wr1_code, sizeof(wr1_code));
        else if(wr_data == SUB) IoTUartWrite(DEMO_UART_NUM2, wr0_code, sizeof(wr0_code));
        hi_sleep(50);
        len = IoTUartRead(DEMO_UART_NUM2, buffer, sizeof(buffer));
        if(len > 0) wr_flag = buffer[2];
    }while(wr_flag != 0x49);
} 

void RFID_power(void)
{
    hi_u8 cap_data[]= {0xBB ,0x00 ,0xB6 ,0x00 ,0x02 ,0x03 ,0x84 ,0x3F ,0x7E  };
    unsigned char buffer[32] = {0};
    int len=0;
    IoTUartWrite(DEMO_UART_NUM2, cap_data, sizeof(cap_data));
    do{
        hi_sleep(50);
        len = IoTUartRead(DEMO_UART_NUM2, buffer, sizeof(buffer));
    }while(len == 0);
}

int RFID_deal(Taurus_Msg *rfid_msg, hi_u8 *data, hi_u16 len)
{
    hi_u16 type_id = data[2]*256+data[3];
    hi_u16 code = data[4]*256+data[5];
    hi_u16 buy_flag = data[6]*256+data[7];
    int i,j,k,m;
    Item_Msg bufffer;
    for(i=0; i<(rfid_msg->type_num) ; i++)
    {   
        if((rfid_msg->item[i].id) == type_id)
        {
            for(j=0; j<(rfid_msg->item[i].num); j++)
            {
                if((rfid_msg->item[i].code[j]) == code)
                    if((buy_flag == 1) && (rfid_state = 2))
                        {
                            buy_flag = 0;
                            for(k=j; k<(rfid_msg->item[i].num); k++)
                                rfid_msg->item[i].code[j] = rfid_msg->item[i].code[j+1];
                            rfid_msg->item[i].num--;
                            rfid_msg->num--;
                            if(type_id >= ITEM_BOUNDARY)
                            {
                                rfid_msg->item[i].weight += commodity_weight;
                                rfid_msg->price -= (rfid_msg->item[i].price)*commodity_weight;
                            }
                            else
                                rfid_msg->price -= rfid_msg->item[i].price;
                            if(rfid_msg->item[i].num == 0)
                            {
                                for(k=i; k<(rfid_msg->type_num); k++)
                                {
                                    memcpy_s( &(rfid_msg->item[k]), sizeof(Item_Msg), &((rfid_msg->item[k+1])), sizeof(Item_Msg) );
                                }
                                rfid_msg->type_num--;               
                            }
                            RFID_write(SUB);
                            rfid_state = 2;
                            return 3;
                        }
                    else    
                        return 1;
            }
            if(rfid_state != 2)
            {
                rfid_msg->item[i].code[j] = code;
                rfid_msg->item[i].num++;
                rfid_msg->num++;
                if(type_id >= ITEM_BOUNDARY)
                {
                    rfid_msg->item[i].weight += commodity_weight;
                    rfid_msg->price += (rfid_msg->item[i].price)*commodity_weight;
                }
                else
                    rfid_msg->price += rfid_msg->item[i].price;
                RFID_write(ADD);
                rfid_state = 3;
                return 2;
            }
        }
    }
    if(rfid_state != 2)
    {
        rfid_state = 1;
        rfid_msg->num++;
        rfid_msg->type_num++;
        rfid_msg->item[i].id = type_id;
        rfid_msg->item[i].num = 1;
        rfid_msg->item[i].code[0] = code;
        if(type_id >= ITEM_BOUNDARY)
        {
            rfid_msg->item[i].weight += commodity_weight;
            rfid_msg->item[i].name = items1_name[type_id - ITEM_BOUNDARY]; 
            rfid_msg->item[i].price = items1_price[type_id - ITEM_BOUNDARY];
            rfid_msg->price += (rfid_msg->item[i].price)*commodity_weight;
        }
        else
        {
            rfid_msg->item[i].name = items0_name[type_id];
            rfid_msg->item[i].price = items0_price[type_id];
            rfid_msg->price += rfid_msg->item[i].price;
        }
        RFID_write(ADD);
        rfid_state = 3;
        return 1;
    }
    return 0;
}

int RFID_Receive(Taurus_Msg *rfid_msg, hi_u8 *uart_data , hi_u16 uart_len)
{ 
    hi_u8 buffer[32];
    hi_u16 pl=0;
    int i,j;
    hi_u8 check_sum;
    hi_u16 crc16;
    for(i=0; i< uart_len; i += (pl+7))
    {
        memcpy_s( buffer, 32, &(uart_data[i]), 32);
        pl=buffer[3]*256 + buffer[4];
        check_sum = 0;
        for(j=1; j<= 4+pl; j++)  check_sum = check_sum + buffer[j];
        if((buffer[0] == 0xbb) && (buffer[6+pl] == 0x7e) && (check_sum == buffer[5+pl]))
            if(buffer[1]==0x01)
            {
                if(buffer[2] == 0xff);   
            }
            else    if(buffer[1] == 0x02)
            {   
                memcpy_s( buffer, 32, &(uart_data[i+6]), 32);
                crc16 = crc16_check(buffer, pl-3);
                if(crc16 == (buffer[pl-3]*256+buffer[pl-2]))
                    RFID_deal(rfid_msg, buffer, pl-5);
            }                       
    }
    return 1;
}
    
void RFID_send()
{
    hi_u8 code[]= { 0xBB ,0x00 ,0x27 ,0x00 ,0x03 ,0x22 ,0x00 ,0x0A ,0x56 ,0x7E };
    IoTUartWrite(DEMO_UART_NUM2, code, sizeof(code));
} 


//1.任务处理函数 
static void* RFID_Task(const char* arg) 
{ 
    int i,j;
    unsigned int len = 0; 
    Uart2GpioCOnfig(); 
    usr_uart_config2();
    (void)arg; 
    RFID_power();
    Taurus_Msg  rfid_msg_now={0}; 
    while (1) {
        if(rfid_flag == 1)
        {
            IoTUartRead(DEMO_UART_NUM2, Rubbish, sizeof(Rubbish));
            RFID_send();
            hi_sleep(2000); 
            len = IoTUartRead(DEMO_UART_NUM2, rfidReadBuff, sizeof(rfidReadBuff));
            printf("\n\nrfid data: ");
            for(i=0; i<len; i++) 
            {
                if(rfidReadBuff[i] == 0xbb) printf("\n");
                printf(" 0x%x ", rfidReadBuff[i]);
            }
            if(len > 0)
                RFID_Receive(&rfid_msg_now, rfidReadBuff , len);
            rfid_flag = 2;
        } 
        else if(rfid_flag == 3)
        {
            rfid_msg_now.price = 0;
            for(i=0; i<(rfid_msg_now.type_num); i++) 
            {
                if(rfid_msg_now.item[i].id >= ITEM_BOUNDARY)
                {
                    rfid_msg_now.price += (rfid_msg_now.item[i].price)*(rfid_msg_now.item[i].weight);printf("\nprice= %.2f weight= %.2f",rfid_msg_now.price,rfid_msg_now.item[i].weight);
                }
                else
                {
                    rfid_msg_now.price += (rfid_msg_now.item[i].price)*(rfid_msg_now.item[i].num);printf("\nprice= %.2f num= %d",rfid_msg_now.price,rfid_msg_now.item[i].num);
                }
            }
            rfid_flag = 0;
            memcpy_s(&rfid_msg_show, sizeof(Taurus_Msg), &rfid_msg_now, sizeof(Taurus_Msg));
            printf("\nprice= %.2f\t price= %.2f",rfid_msg_now.price,rfid_msg_show.price);
        } 
        //printf("\nprice= %.2f\t price= %.2f",rfid_msg_now.price,rfid_msg_show.price);
        for(i=0; i<(rfid_msg_show.type_num); i++) 
            {
                printf("\nname=%s\t num=%d code=",rfid_msg_show.item[i].name,rfid_msg_show.item[i].num);
                for(j=0; j<rfid_msg_show.item[i].num; j++)   printf("%d ",rfid_msg_show.item[i].code[j]);
            }   
        hi_sleep(2000); 
    } 
  
    return NULL; 
} 
 
//2.任务入口函数 
static void RFID_Demo(void) 
{ 
    osThreadAttr_t attr = {0}; 
 
    printf("[UartDemo] UartDemo2_Entry()\n"); 
    IoTWatchDogDisable();
    attr.name = "RFID_UartDemo"; 
    attr.attr_bits = 0U; 
    attr.cb_mem = NULL; 
    attr.cb_size = 0U; 
    attr.stack_mem = NULL; 
    attr.stack_size = 9056;//堆栈大小 
    attr.priority = 23;//优先级 
 
    if (osThreadNew((osThreadFunc_t)RFID_Task, NULL, &attr) == NULL) 
    { 
        printf("[UartDemo] Falied to create UartDemo_Task!\n"); 
    } 
} 
 
//3.注册模块 
SYS_RUN(RFID_Demo); 
